package cn.tianyigps.m7.netty;

import cn.tianyigps.m7.beans.Equipment;
import cn.tianyigps.m7.factorys.EquipmentFactory;
import cn.tianyigps.m7.utils.MessageCoding;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;
import java.util.Optional;

/**
 * Created with IDEA
 *
 * @description: 分包逻辑
 *
 * @author: cui.guibin
 *
 * @create: 2019/3/8 14:28
 **/
public class EquipmentDecoder extends ByteToMessageDecoder {

    Logger log = LogManager.getLogger(EquipmentDecoder.class);
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf bf, List<Object> list) {

        ByteBuf byteBuf = bf.copy();
        TYChannelPipeline pipeline = (TYChannelPipeline) ctx.pipeline();
        byte[] bytes = MessageCoding.getBytes(byteBuf);
        String strData = MessageCoding.bytesToHexString(bytes);
        Equipment equipment = pipeline.getEquipment();

        if (!Optional.ofNullable(equipment).isPresent()) {
            equipment = EquipmentFactory.equipmentInstance(ctx,strData);
        }
        if (!Optional.ofNullable(equipment).isPresent()){
            bf.clear();
            return;
        }

        // 初始化，分包
        EquipmentFactory.initPipeline(ctx,bf,list);
        // 回复
        byte[] response = equipment.response(strData);
        if (response !=null && response.length > 0)
            ctx.writeAndFlush(Unpooled.copiedBuffer(response));
        // 心跳回复
        byte[] generalResponse = equipment.generalResponse(strData);
        if (generalResponse !=null && generalResponse.length > 0)
            ctx.writeAndFlush(Unpooled.copiedBuffer(generalResponse));
//        // 指令下发
//        byte[] command = equipment.command(strData);
//        if (command !=null && command.length > 0)
//            ctx.writeAndFlush(Unpooled.copiedBuffer(command));

    }
}
